<template>
  <div class="tacitly">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      size="small"
    >
      <el-form-item label="作者" prop="author">
        <el-input v-model="form.author" placeholder="请输入作者"/>
      </el-form-item>
      <el-form-item label="发布日期" prop="publicTime">
        <el-date-picker value-format="yyyy-MM-dd" v-model="form.publicTime" type="date"
                        placeholder="发布日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="标签" prop="label">
        <el-select v-model="form.label" placeholder="请选择标签">
          <el-option
            v-for="item in dictList"
            :key="item.id"
            :label="item.dictLabel"
            :value="item.dictLabel"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="新闻图片" prop="newsPic" class="upload-form-item">
        <div>
          <el-upload
            list-type="picture-card"
            accept=".png, .jpg"
            :limit="coverImageLimit"
            :class="{hideAdd:coverAddhide}"
            :file-list="coverImag"
            action
            :http-request="HandleUploadSelf"
            :before-upload="handleBeforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :on-preview="handlepreview"
            :on-change="onChange"
            :on-error="onError"
          >
            <i class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
          <el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>

          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="form.newsPic" alt/>
          </el-dialog>
        </div>
        <span v-if="!coverAddhide" class="span-tip">仅支持.png .jpg格式</span>
      </el-form-item>

      <!--<el-form-item label="新闻状态" prop="status">-->
      <!--  <el-radio size="mini" v-model="form.status" label="0">正常</el-radio>-->
      <!--  <el-radio size="mini" v-model="form.status" label="1">关闭</el-radio>-->
      <!--</el-form-item>-->
      <el-form-item label="新闻类型" prop="typeId" v-if="userRole!=='zhencexinwen'">
        <el-select v-model="form.typeId" placeholder="请选择新闻类型">
          <el-option
            v-for="item in selecTypeList"
            :key="item.id"
            :label="item.typeName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="新闻标题" prop="newsTitle">
        <el-input v-model="form.newsTitle" placeholder="请输入新闻标题"/>
      </el-form-item>
      <el-form-item label="新闻简介" prop="newsIntroduction">
        <el-input
          v-model="form.newsIntroduction"
          placeholder="请输入新闻简介"
        />
      </el-form-item>
      <el-form-item label="原文地址" prop="originalAddress">
        <el-input v-model="form.originalAddress" placeholder="请输入原文地址"/>
      </el-form-item>
      <el-form-item label="新闻内容">
        <editor v-model="form.newsContent" :min-height="192"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {addNews, getNews, updateNews} from "@/api/portal/news";
import {listType} from "@/api/portal/type";
import Editor from "@/components/Editor";
import {fileupload} from "@/api/menu";
import {listData} from "@/api/system/dict/data";
import axios from "axios";
import {getToken} from "@/utils/auth";

export default {
  components: {
    Editor,
  },
  data() {
    return {
      // 表单参数
      form: {
        status: "0",
      },
      // 表单校验
      rules: {
        typeId: [
          {required: true, message: "新闻类型不能为空", trigger: "blur"},
        ],
        newsTitle: [
          {required: true, message: "新闻标题不能为空", trigger: "blur"},
        ],
        publicTime: [
          {required: true, message: "发布时间不能为空", trigger: "blur"},
        ],
        label: [
          {required: true, message: "标签不能为空", trigger: "blur"},
        ],
      },
      userRole: 'all',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      selecTypeList: [],
      // 上传图片
      dialogVisible: false, // 查看封面缩略图 dialog
      coverImageLimit: 1, // 封面图的个数
      coverAddhide: false, // 封面加号隐藏
      coverImag: [],
      dictList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/file/upload",
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
    };
  },
  beforeRouteEnter(to, from, next) {
    if (to.query.id) {
      to.meta.title = "编辑新闻列表";
    } else {
      to.meta.title = "新增新闻列表";
    }
    next();
  },
  beforeRouteLeave(to, from, next) {
    this.$store.dispatch("tagsView/delView", this.$route);
    next();
  },
  created() {
    this.userRole = this.$store.getters.roles[0]
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id;
      this.getnewsInfo();
    }
  },
  mounted() {
    this.getnewstypeList();
    this.getdictDataList();
  },
  methods: {
    // 获取新闻详情
    getnewsInfo() {
      getNews(this.form.id).then((response) => {
        this.form = response.data;
        if (this.isEmpty(this.form.newsPic)) {
          this.coverImag = [];
        } else {
          this.coverImag = [{url: this.form.newsPic}];
          this.coverAddhide = true;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.returntomenu();
      this.reset();
    },
    handleBeforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 3;
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
      console.log("isLt2M",isLt2M)
      if (!isLt2M) {
        this.$message.error('封面图片大小不能超过 3MB!');
        this.loading.close();
      }
      return isLt2M;
    },
    handleUploadSuccess(){
      // this.loading.close();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        status: "0",
        newsPic: null,
        typeId: null,
        author: null,
        newsTitle: null,
        newsIntroduction: null,
        originalAddress: null,
        newsContent: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        publicTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.userRole === "zhencexinwen") {
            this.form.typeId = 3
          }
          if (this.form.id != null) {
            updateNews(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.returntomenu();
            });
          } else {
            addNews(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.returntomenu();
            });
          }
        }
      });
    },

    /** 查询新闻类型列表 */
    getnewstypeList() {
      listType(this.queryParams).then((response) => {
        this.selecTypeList = response.rows;
      });
    },
    // 封面自定义上传图片
    HandleUploadSelf(file, fileList) {

      axios({
        method: "post",
        url: this.uploadFileUrl,
        data: this.formData({file: file.file}),
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + getToken(),
        },
        //上传进度
        onUploadProgress: (progressEvent) => {
          this.progressFlag = true;
          this.loadProgress =
            ((progressEvent.loaded / progressEvent.total) * 100) | 0;
          if (this.loadProgress >= 99) {
            this.loadProgress = 99;
          }
        },
      })
        .then((resf) => {
          let res = resf.data;
          if (res.code === 200) {
            this.progressFlag = false;
            this.loadProgress = 100;
            this.form.newsPic = "http://" + res.data.url;
            this.loading.close();
            this.$message.success("上传成功");
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          console.log(error);
        });

      // fileupload(this.formData({ file: file.file })).then((res) => {
      //   if (res.code === 200) {
      //     this.msgSuccess(res.msg);
      //     this.form.newsPic = "http://" + res.data.url;
      //   }
      // });
    },
    // 封面图片移除
    handleRemove(file, fileList) {
      console.log(fileList, "封面图片移除");
      this.coverImag = fileList;
      this.form.newsPic = ""
      this.coverAddhide = this.coverImag.length >= this.coverImageLimit;
    },
    onError(){
      this.loading.close();
    },
    // 封面图片发生变化
    onChange(file, fileList) {
      console.log(fileList, "封面图片发生变化");
      this.coverImag = fileList;
      this.coverAddhide = this.coverImag.length >= this.coverImageLimit;
    },
    // 封面缩略图
    handlepreview(file) {
      this.dialogVisible = true;
    },

    /** 查询字典数据列表 */
    getdictDataList() {
      listData({dictType: "news_label"}).then((response) => {
        if (this.userRole == "zhencexinwen") {
          this.dictList = response.rows.slice(5, 8)

        } else {
          this.dictList = response.rows;
        }

        console.log(this.dictList)

      });

    },
  },
};
</script>
<style scoped lang="scss">
.tacitly .hide .el-upload--picture-card {
  display: none;
}

.tacitly {
  padding: 20px;
  box-sizing: border-box;
  width: 50%;

  .dialog-footer {
    display: flex;
    justify-content: center;
  }
}

::v-deep .el-upload-list__item {
  width: auto;
  height: auto;
  min-width: 100px;
  min-height: 100px;
  max-width: 600px;
  line-height: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

::v-deep .hideAdd .el-upload--picture-card {
  display: none !important; /* 上传按钮隐藏 */
}
</style>
